<template>
  <div id="addQuestionView">
    <a-form
      :model="form"
      size="large"
      :wrapper-col-style="{ padding: '10px' }"
      :layout="'horizontal'"
    >
      <!----------题目标题------------------------>
      <a-form-item field="title" label="题目标题">
        <a-input
          class="inputText"
          v-model="form.title"
          placeholder="请输入标题"
        />
      </a-form-item>
      <!----------题目标签------------------------>
      <a-form-item field="tag" label="题目标签">
        <a-input-tag
          class="inputText"
          v-model="form.tags"
          placeholder="请输入标签"
          allow-clear
        />
      </a-form-item>
      <!----------题目内容------------------------>
      <a-form-item field="content" label="题目内容">
        <div class="mdEditor">
          <MdEditor :value="form.content" :handle-change="changeContent" />
        </div>
      </a-form-item>
      <!----------题目答案------------------------>
      <a-form-item field="answer" label="答案">
        <div class="mdEditor">
          <MdEditor :value="form.answer" :handle-change="changeAnswer" />
        </div>
      </a-form-item>
      <!----------题目配置------------------------>
      <a-form-item label="题目配置" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" SpaceSize="small">
          <a-form-item field="judgeConfig.timeLimit" label="时间限制">
            <a-input-number
              class="inputNumber"
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              mode="button"
              size="large"
              min="0"
            />
            ms
          </a-form-item>
          <a-form-item field="judgeConfig.memoryLimit" label="内存限制">
            <a-input-number
              class="inputNumber"
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制限制"
              mode="button"
              size="large"
              min="0"
            />
            mb
          </a-form-item>
          <a-form-item field="judgeConfig.stackLimit" label="堆栈限制">
            <a-input-number
              class="inputNumber"
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制"
              mode="button"
              size="large"
              min="0"
            />
            mb
          </a-form-item>
        </a-space>
      </a-form-item>

      <!----------题目用例------------------------>
      <a-form-item field="judgeCase" label="测试用例">
        <a-space direction="vertical" SpaceSize="small">
          <a-form-item
            v-for="(judgeCaseItem, index) of form.judgeCase"
            :field="`form.judgeCase[${index}]`"
            :key="index"
            no-style
          >
            <!----------输入样例------------------------>
            <a-form-item
              :field="`form.judgeCase[${index}].input`"
              :label="`输入用例${index + 1}`"
              :key="index"
            >
              <a-textarea
                class="inputTextArea"
                v-model="judgeCaseItem.input"
                placeholder="请输入输入用例"
                :auto-size="{
                  minRows: 6,
                }"
                :ref="(el: ArcoTextareaInstance) => setCaseInputRef(el, index as number)"
              />
            </a-form-item>
            <!----------输出样例------------------------>
            <a-form-item
              :field="`form.judgeCase[${index}].output`"
              :label="`输出用例${index + 1}`"
              :key="index"
            >
              <a-textarea
                class="inputTextArea"
                v-model="judgeCaseItem.output"
                placeholder="请输入输出用例"
                :auto-size="{
                  minRows: 6,
                  minCols: 50,
                }"
              />
            </a-form-item>
            <a-button
              status="danger"
              @click="handleDeleteJudgeCase(index as number)"
              :style="{ marginLeft: '10px' }"
              >删除
            </a-button>
            <a-divider />
          </a-form-item>

          <div style="margin-top: 32px">
            <a-button
              ref="addCaseButtonRef"
              status="success"
              type="outline"
              @click="handleAddJudgeCase"
              >新增测试用例
            </a-button>
          </div>
        </a-space>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          style="width: 200px; font-size: 16px"
          @click="submit"
          >{{ updatePage ? "更新" : "提交" }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeMount, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { Textarea } from "@arco-design/web-vue";
import { QuestionControllerService } from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { useRoute } from "vue-router";

/**
 * 题目表单
 */
const form = ref({
  title: "",
  tags: [],
  answer: "",
  content: "",
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 400,
    timeLimit: 400,
  },
} as any);

const route = useRoute();
//如果地址中包含update则为更新题目
const updatePage = route.path.includes("update");
console.log("hjjj");

/**
 * 根据题目id加载数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const rs = await QuestionControllerService.getQuestionByIdUsingGet(id as any);
  if (rs.code === 0) {
    form.value = rs.data;
    //对获取的数据进行转json处理
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags);
    }
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 400,
        timeLimit: 400,
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig);
    }
  } else {
    message.error("题目获取加载失败" + rs.message);
  }
};

onBeforeMount(() => {
  loadData();
});

/**
 * 修改表单答案
 * @param v
 */
const changeAnswer = (v: string) => {
  form.value.answer = v;
};
/**
 * 修改表单内容
 * @param v
 */
const changeContent = (v: string) => {
  form.value.content = v;
};

/**
 * 提交表单
 */
const submit = async () => {
  if (updatePage) {
    console.log(form.value);
    let updateRs = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    );
    if (updateRs.code === 0) {
      message.success("更新成功");
    } else {
      message.error("更新失败:" + updateRs.message);
    }
    return;
  }
  let addResult = await QuestionControllerService.addQuestionUsingPost(
    form as any
  );
  if (addResult.code === 0) {
    message.success("添加成功");
  } else {
    message.error("添加失败:" + addResult.message);
  }
};

// 获取 a-textarea 的实例类型
type ArcoTextareaInstance = InstanceType<typeof Textarea>;

const caseInputRefs = ref<ArcoTextareaInstance[]>([]);
const addCaseButtonRef = ref();
const setCaseInputRef = (el: ArcoTextareaInstance | null, index: number) => {
  if (el) {
    caseInputRefs.value[index] = el;
  }
};
const handleAddJudgeCase = () => {
  const newIndex = form.value.judgeCase.length;
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
  nextTick(() => {
    const textareaWrapper = caseInputRefs.value[newIndex];
    if (textareaWrapper && textareaWrapper.$el) {
      const textareaElement = textareaWrapper.$el.querySelector("textarea");
      if (textareaElement) {
        textareaElement.focus();
      }
    }

    setTimeout(() => {
      const buttonElement =
        addCaseButtonRef.value?.$el || addCaseButtonRef.value;
      if (buttonElement && "scrollIntoView" in buttonElement) {
        buttonElement.scrollIntoView({ behavior: "smooth", block: "center" });
      }
    }, 100); // 延迟 100ms 执行,确保添加按钮已经渲染完成,之后滚动到该按钮位置
  });
};
/**
 * 删除测试用例
 * @param index
 */
const handleDeleteJudgeCase = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};
</script>

<style scoped>
#addQuestionView {
}

.mdEditor {
  width: 1000px;
}

.inputNumber {
  min-width: 500px;
}

.inputText {
  width: 1000px;
}

.inputTextArea {
  min-width: 500px;
}
</style>
